package com.ihelp.rest.mis.platform.dao;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.ihelp.rest.base.hibernate4.BaseHibernateDao;
import com.ihelp.rest.base.po.Page;
import com.ihelp.rest.mis.pojo.SiteType;

@Repository
public class SiteTypeDao extends BaseHibernateDao<SiteType, String>{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 查询网站分类Page
	 * @param queryCondition
	 * @param start
	 * @param pageSize
	 * @param sort
	 * @param order
	 * @return
	 */
	public Page<SiteType> querySiteTypePage(SiteType queryCondition,int start,int pageSize,String sort, String order){
		StringBuilder hql = new StringBuilder();
		ArrayList<Object> list = new ArrayList<Object>();
		hql.append("from SiteType t where 1=1 ");
		if(StringUtils.isNotBlank(queryCondition.getParentcode())){
			hql.append(" and t.parentcode=?");
			list.add(queryCondition.getParentcode());
		}
		if(StringUtils.isNotBlank(queryCondition.getTypename())){
			hql.append(" and t.typename like ?");
			list.add("%"+queryCondition.getTypename()+"%");
		}
		if(StringUtils.isNotBlank(sort))
			hql.append(" order by ").append(sort).append(" ").append(order);
		return this.page(hql.toString(), start, pageSize, (Object[])list.toArray());
	}
	
	public List<SiteType> querySiteTypeByPid(String parengcode){
		return this.list("from SiteType a where a.parentcode=? order by typecode", parengcode);
	}
	
	public SiteType querySiteTypeByCode(String parengcode){
		return this.unique("from SiteType a where a.typecode=?", parengcode);
	}
	
	public String getNewCode(String parentcode){
		String sRet = "";
		String sql = "select max(typecode) as newcode from sitetype t where t.parentcode='"+parentcode+"'"; 
		List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql);
		if(result.size()>0){
			for (Map<String, Object> one : result) {
				if(StringUtils.isNotBlank((one.get("newcode")==null)?"":one.get("newcode").toString()))
					sRet = String.valueOf((Long.valueOf(one.get("newcode").toString())+1));
				else{
					if(parentcode.equals("0"))
						sRet = "10";
					else
						sRet = parentcode+"01";
				}
			}
		}else{
			if(parentcode.equals("0"))
				sRet = "10";
			else
				sRet = parentcode+"01";
		}
		return sRet;
	}
	
}
